<template>
    <h1>用户投资页面</h1>

    <table class="table table-bordered" border="1">
        <tr>
            <td>投资名称</td>
            <td>
                {{ info.I_Name }}
            </td>
        </tr>

        <tr>
            <td>投资总金额</td>
            <td>
                {{ info.I_Budget }}
            </td>
        </tr>

        <tr>
            <td>已投金额</td>
            <td>
                {{ info.I_Receive }}
            </td>
        </tr>

        <tr>
            <td>剩余金额</td>
            <td>
                {{ info.I_Residue }}
            </td>
        </tr>

        <tr>
            <td>投资金额</td>
            <td>
                <input type="text" v-model="Money" @change="GetMoney" >
            </td>
        </tr>

        <tr>
            <td>预计最高收益</td>
            <td>
                {{ Iapy.toFixed(2) }}CNY
            </td>
        </tr>

        <tr>
            <td colspan="2" style="text-align: center;" >
                <input type="button" value="确认投资" @click="AddUserInvest" >
            </td>
        </tr>

    </table>

</template>

<script setup lang="ts">
import { ref,onMounted } from 'vue';
import axios from 'axios';
import { useRouter,useRoute } from 'vue-router';
import {useUserStore} from '../../store/index.ts'

const useStore = useUserStore();

const router = useRouter();
const route = useRoute();

console.log(route.params.Id);

alert(useStore.Uid)


//用于反填显示的数据
const info = ref({
    I_Id:'',
    I_Name:'',
    I_Budget:'',
    I_Receive:'',
    I_Residue:'',
})

const Money = ref("");
const Iapy = ref(0)

onMounted (()=>{
    SaveData()
})
//反填功能
const SaveData = ()=>{
    axios({
        url:'http://localhost:56707/api/Invest/SaveData',
        method:'get',
        params:{
            Id:route.params.Id
        }
    })
    .then(res=>{
        console.log(res.data);
        info.value = res.data;
    })
    .catch(err=>{
        console.log(err);
    })
}

const GetMoney = ()=>{
    Iapy.value = Number(Money.value)*1.3/100  
}

const AddUserInvest =()=>{
    if(Money.value==""){
        alert("用户投资金额不能为空");
        return;
    }

    if( Number(Money.value)<=0 || Number(Money.value) > Number(info.value.I_Residue)  ){
        alert("用户投资金额不能为空或大于剩余金额");
        return;
    }

    axios({
        url:'http://localhost:56707/api/Invest/AddUserInvest',
        method:'post',
        data:{
            I_Id:route.params.Id,//投资编号
            U_Id:useStore.Uid,//用户编号
            UT_Money:Money.value,//用户投资金额
        }
    })
    .then(res=>{
        if(res.data>0){
            alert('用户投资成功');
            router.push('/ShowUserInvest')
        }
        else{
            alert('用户投资失败');
            return;
        }
    })
    .catch(err=>{
        console.log(err);
    })
}


</script>
